package com.baymax.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baymax.entity.vo.SysUserVO;
import com.baymax.security.entity.OnlineUser;
import com.baymax.security.entity.SecurityUser;

import java.util.Date;

/**
 * JWT工具类
 *
 * @Author: baymax
 * @CreateTime: 2023/4/3 11:57
 * @Version: 1.0
 */
public class JwtUtil {

    /**
     * 签名密钥
     */
    private final static Algorithm SECRET = Algorithm.HMAC256("2xWFf5fwD6oZQMhFofGwwOqLoWosMB");

    /**
     * 创建token令牌
     */
    public static String createToken(Long userId) {
        try {
            return JWT.create()
                    .withIssuedAt(DateUtil.now())
                    .withJWTId(userId.toString())
                    .sign(SECRET);
        } catch (JWTCreationException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 解析token令牌，获取用户id
     */
    public static String getUserIdByToken(String token) {
        return parseToken(token).getId();
    }

    /**
     * 解析token令牌，获取用户id
     */
    public static Date getTokenCreateDate(String token) {
        return parseToken(token).getIssuedAt();
    }

    /**
     * 解析token
     */
    private static DecodedJWT parseToken(String token) {
        DecodedJWT decodedJWT;
        try {
            JWTVerifier verifier = JWT.require(SECRET)
                    .build();
            decodedJWT = verifier.verify(token);
        } catch (JWTVerificationException e){
            throw new RuntimeException(e.getMessage());
        }
        if (StrUtil.isBlank(decodedJWT.getId())) {
            throw new RuntimeException("token解析异常");
        }
        return decodedJWT;
    }

    /**
     * 构建redis中在线用户key
     */
    public static String buildOnlineUserKey(String key, Long userId, String token) {
        return key + (ObjectUtil.isNotNull(userId) ? userId : getUserIdByToken(token)) + StrUtil.COLON + token;
    }

    /**
     * 构建认证用户
     *
     * @param onlineUser 在线用户信息
     */
    public static SecurityUser buildSecurityUser(OnlineUser onlineUser) {
        SecurityUser securityUser = new SecurityUser();
        SysUserVO sysUserVO = onlineUser.getSysUserVO();
        securityUser.setUserId(sysUserVO.getUserId());
        securityUser.setUsername(sysUserVO.getUsername());
        securityUser.setRoleVOList(onlineUser.getRoleVOList());
        securityUser.setMenuPermissionList(onlineUser.getMenuPermissionList());
        return securityUser;
    }

}
